package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.PageObject;
import com.cy.pj.sys.dao.SysRoleDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysRole;
import com.cy.pj.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService {
   @Autowired
   private SysRoleDao sysRoleDao;

   @Autowired
   private SysRoleMenuDao sysRoleMenuDao;

   @Autowired
   private SysUserRoleDao sysUserRoleDao;

    @Override
    public int deleteObject(Integer id) {
        //1.验证数据的合法性
        if(id==null||id<=0)
            throw new IllegalArgumentException("请先选择");
        //3.基于id删除关系数据
        sysRoleMenuDao.deleteObjectsByRoleId(id);
        sysUserRoleDao.deleteObjectsByRoleId(id);
        //4.删除角色自身
        int rows=sysRoleDao.deleteObject(id);
        if(rows==0)
            throw new ServiceException("此记录可能已经不存在");
        //5.返回结果
        return rows;
    }

    @Override
    public PageObject<SysRole> findPageObjects(String name, Integer pageCurrent) {
        if(pageCurrent==null||pageCurrent<1)
            throw new IllegalArgumentException("当前页码值无效");
        //2.查询总记录数并进行校验
        int rowCount=sysRoleDao.getRowCount(name);
        if(rowCount==0)
            throw new ServiceException("没有找到对应记录");
        //3.查询当前页记录
        int pageSize=2;
        int startIndex=(pageCurrent-1)*pageSize;
        List<SysRole> records=
                sysRoleDao.findPageObjects(name,
                        startIndex, pageSize);
        //4.对查询结果进行封装并返回
        return new PageObject<>(pageCurrent, pageSize,
                rowCount, records);
    }
}
